<template>
  <ElDialog
    :title="dialogTitle"
    :model-value="visible"
    @update:model-value="handleCancel"
    width="800px"
    align-center
    class="menu-dialog"
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="85px">
      <ElFormItem label="菜单类型">
        <!-- 菜单类型创建后不可修改，仅用于展示当前类型 -->
        <ElRadioGroup v-model="menuType" disabled>
          <ElRadioButton value="menu" label="menu">菜单</ElRadioButton>
          <ElRadioButton value="button" label="button">权限</ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>

      <!-- 菜单表单 -->
      <template v-if="menuType === 'menu'">
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="上级菜单" prop="parentId">
              <ElTreeSelect 
                v-model="form.parentId" 
                :data="processedMenuOptions" 
                :props="treeProps"
                placeholder="请选择上级菜单" 
                clearable 
                check-strictly
                :render-after-expand="false"
                node-key="value"
                style="width: 100%"
                @change="handleParentChange"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="菜单名称" prop="name">
              <ElInput v-model="form.name" placeholder="菜单名称" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="路由地址" prop="path">
              <template #label>
                <span>路由地址</span>
                <el-tooltip 
                  v-if="parentMenuPath" 
                  :content="'完整路径: ' + fullMenuPath" 
                  placement="top"
                >
                  <i class="el-icon-question" style="margin-left: 4px; color: #409eff;"></i>
                </el-tooltip>
              </template>
              <div style="display: flex; align-items: center;">
                <span v-if="parentMenuPath" class="path-prefix">{{ parentMenuPath }}/</span>
                <ElInput 
                  v-model="form.path" 
                  placeholder="请输入路由地址" 
                  :style="{ flex: 1 }"
                />
              </div>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="组件路径" prop="component">
              <ElInput v-model="form.component" placeholder="组件路径" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="前端权限" prop="webPerms">
              <ElInput v-model="form.webPerms" placeholder="前端权限标识" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="后端权限" prop="apiPerms">
              <ElInput v-model="form.apiPerms" placeholder="后端权限标识" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="图标" prop="icon">
              <ArtIconSelector v-model="form.icon" :iconType="iconType" width="100%" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="菜单排序" prop="sort">
              <ElInputNumber
                v-model="form.sort"
                style="width: 100%"
                :min="1"
                controls-position="right"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="外部链接" prop="frameUrl">
              <ElInput v-model="form.frameUrl" placeholder="外部链接/内嵌地址(https://www.baidu.com)" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="20">
          <ElCol :span="6">
            <ElFormItem label="是否启用" prop="visibleFlag">
              <ElSwitch 
                v-model="form.visibleFlag" 
                :active-value="1" 
                :inactive-value="0"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="6">
            <ElFormItem label="是否内嵌" prop="frameFlag">
              <ElSwitch v-model="form.frameFlag" :active-value="1" :inactive-value="0" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </template>

      <!-- 权限表单 -->
      <template v-if="menuType === 'button'">
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="上级菜单" prop="parentId">
              <ElTreeSelect 
                v-model="form.parentId" 
                :data="processedMenuOptions" 
                :props="treeProps"
                placeholder="请选择上级菜单" 
                clearable 
                check-strictly
                :render-after-expand="false"
                node-key="value"
                style="width: 100%"
                @change="handleParentChange"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="权限名称" prop="authName">
              <ElInput v-model="form.authName" placeholder="权限名称" />
            </ElFormItem>
          </ElCol>
        </ElRow>
        
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="前端权限" prop="webPerms">
              <ElInput v-model="form.webPerms" placeholder="前端权限标识" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="后端权限" prop="apiPerms">
              <ElInput v-model="form.apiPerms" placeholder="后端权限标识" />
            </ElFormItem>
          </ElCol>
        </ElRow>
        
        <ElRow :gutter="20">
          <ElCol :span="12">
            <ElFormItem label="权限排序" prop="authSort">
              <ElInputNumber
                v-model="form.authSort"
                style="width: 100%"
                :min="1"
                controls-position="right"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </template>
    </ElForm>

    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="handleCancel">取 消</ElButton>
        <ElButton type="primary" @click="handleSubmit" :loading="loading">确 定</ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { IconTypeEnum } from '@/enums/appEnum'
  import { formatMenuTitle } from '@/router/utils/utils'
  import type { AppRouteRecord } from '@/types/router'
  import {
    apiRbacMenuUpdateDataUsingPost
  } from '@/api'

  /**
   * 菜单表单数据接口
   */
  interface MenuFormData {
    id: number
    name: string
    path: string
    webPerms: string
    apiPerms: string
    component: string
    icon: string
    visibleFlag: number
    sort: number
    frameFlag: number
    frameUrl: string
    disabledFlag: number
    authName: string
    authSort: number
    parentId: number | null
  }

  /**
   * 组件属性接口
   */
  interface Props {
    visible: boolean
    editData?: AppRouteRecord | any
    type?: 'menu' | 'button'
    menuOptions?: any[]
  }

  /**
   * 组件事件接口
   */
  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit', data: MenuFormData): void
    (e: 'refresh'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    visible: false,
    type: 'menu',
    menuOptions: () => []
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()
  const menuType = ref<'menu' | 'button'>(props.type)
  const iconType = ref(IconTypeEnum.UNICODE)
  const loading = ref(false)

  /**
   * 表单数据
   */
  const form = reactive<MenuFormData>({
    id: 0,
    name: '',
    path: '',
    webPerms: '',
    apiPerms: '',
    component: '',
    icon: '',
    visibleFlag: 1,           
    sort: 1,
    frameFlag: 0,
    frameUrl: '',
    disabledFlag: 0,
    authName: '',
    authSort: 1,
    parentId: null
  })

  /**
   * 树形结构配置
   */
  const treeProps = {
    children: 'children',
    label: 'label',
    value: 'value'
  }

  /**
   * 处理后的菜单选项数据
   */
  const processedMenuOptions = computed(() => {
    if (!props.menuOptions || props.menuOptions.length === 0) {
      return [];
    }

    if (props.menuOptions.length > 0) {
      const firstItem = props.menuOptions[0];
      if (firstItem.children) {
        const processTreeNode = (node: any): any => {
          if (!node) return null;
          
          const processedNode = {
            ...node,
            label: node.menuName || node.label || '',
            value: (node.id !== undefined && node.id !== null) ? Number(node.id) : null,
          };

          if (node.children && Array.isArray(node.children) && node.children.length > 0) {
            processedNode.children = node.children.map(processTreeNode)
              .filter((child: any) => child !== null);
          } else {
            processedNode.children = [];
          }

          return processedNode;
        };

        const treeData = props.menuOptions.map(processTreeNode)
          .filter((node: any) => node !== null);
        
        if (props.editData && props.editData.id) {
          return filterTreeData(treeData, props.editData.id);
        }
        
        return treeData;
      } else {
          const buildTreeFromPaths = (flatData: any[]) => {
          // 使用Map替代对象
          const nodeMap = new Map();
          const roots: any[] = [];

          // 创建节点映射
          flatData.forEach(item => {
            nodeMap.set(item.menuPath, {
              ...item,
              label: item.menuName || item.label || '',
              value: item.id !== undefined ? Number(item.id) : null,
              children: []
            });
          });

          // 构建树形结构
          flatData.forEach(item => {
            const node = nodeMap.get(item.menuPath);
            if (!node) return;

            const lastSlashIndex = item.menuPath.lastIndexOf('/');
            if (lastSlashIndex > 0) {
              const parentPath = item.menuPath.substring(0, lastSlashIndex);
              const parent = nodeMap.get(parentPath);
              if (parent) {
                parent.children.push(node);
              } else {
                roots.push(node);
              }
            } else {
              roots.push(node);
            }
          });

          return roots;
        };

        // 构建树形结构
        const treeData = buildTreeFromPaths(props.menuOptions);

        // 如果是编辑状态，需要过滤掉当前菜单及其子菜单，避免循环引用
        if (props.editData && props.editData.id) {
          return filterTreeData(treeData, props.editData.id);
        }

        return treeData;
      }
    }

    return [];
  });

  /**
   * 过滤树形数据，移除指定节点及其子节点
   * @param treeData 树形数据
   * @param excludeId 需要排除的节点ID
   * @returns 过滤后的树形数据
   */
  const filterTreeData = (treeData: any[], excludeId: number): any[] => {
    return treeData.filter(node => {
      if (node.value === excludeId || node.id === excludeId) {
        return false;
      }
      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        node.children = filterTreeData(node.children, excludeId);
      }
      return true;
    });
  };

  /**
   * 父级菜单路径计算属性
   */
  const parentMenuPath = computed(() => {
    if (form.parentId === 0) return '';
    if (form.parentId === null || form.parentId === undefined || !props.menuOptions) return '';
    const parent = props.menuOptions.find(item => item.id === form.parentId);
    return parent ? parent.menuPath : '';
  })

  /**
   * 完整菜单路径计算属性
   */
  const fullMenuPath = computed(() => {
    if (!form.path) return parentMenuPath.value || '/';
    
    const cleanPath = form.path.replace(/^\/+|\/+$/g, '');
    if (!parentMenuPath.value) return `/${cleanPath}`;
    
    return `${parentMenuPath.value.replace(/\/$/, '')}/${cleanPath}`;
  })

  /**
   * 对话框标题计算属性
   */
  const dialogTitle = computed(() => {
    const type = menuType.value === 'menu' ? '菜单' : '权限'
    return `编辑${type}`
  })

  /**
   * 动态表单验证规则
   */
  const rules = computed<FormRules>(() => {
    const baseRules = {
      parentId: [{ required: false, message: '请选择上级菜单', trigger: 'change' }]
    }

    if (menuType.value === 'menu') {
      return {
        ...baseRules,
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }]
      }
    }
    return {
      ...baseRules,
      authName: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ]
    }
  })

  /**
   * 上级菜单变更处理函数
   * @param parentId 上级菜单ID
   */
  const handleParentChange = (parentId: number | null) => {
    if (parentId === null || parentId === undefined) return;
    
    if (parentId === 0) {
      form.path = form.path.replace(/^\//, ''); 
      return;
    }

    const parent = props.menuOptions?.find(item => item.id === parentId);
    if (!parent || !parent.menuPath) {
      form.path = ''; 
      return;
    }

    const parentPath = parent.menuPath.replace(/\/$/, '');
    if (form.path.startsWith(parentPath + '/')) {
      form.path = form.path.replace(new RegExp(`^${parentPath}/`), '');
    }
  }

  /**
   * 重置表单
   */
  const resetForm = () => {
    formRef.value?.resetFields();
    Object.assign(form, {
      id: 0,
      name: '',
      path: '',
      webPerms: '',
      apiPerms: '',
      component: '',
      icon: '',
      visibleFlag: 1,
      sort: 1,
      frameFlag: 0,
      frameUrl: '',
      disabledFlag: 0,
      authName: '',
      authSort: 1,
      parentId: null
    });
  }
  
  /**
   * 初始化表单
   */
  const initForm = () => {
    resetForm();
    if (props.editData) {
      nextTick(() => {
        loadFormData();
      });
    }
  }

  /**
   * 统一获取字段值（优先直接属性，回退到meta）
   */
  const getFieldValue = (source: any, field: string) => {
    if (source[field] !== undefined) return source[field];
    const metaField = field.replace('menu', '').toLowerCase();
    if (source.meta && source.meta[metaField] !== undefined) {
      return source.meta[metaField];
    }
    if (field === 'title' && source.meta && source.meta.title) {
      return source.meta.title;
    }
    
    return '';
  };

  /**
   * 加载表单数据
   */
  const loadFormData = () => {
    if (!props.editData) return;

    const row = props.editData;

    if (props.type === 'menu') {
      form.id = row.id || 0;
      form.name = getFieldValue(row, 'menuName') || formatMenuTitle(getFieldValue(row, 'title') || '');
      form.path = (row.menuPath || row.path || '').replace(parentMenuPath.value, '').replace(/^\//, '');
      form.parentId = row.menuParentId === 0 ? 0 : (row.menuParentId ?? null);

      form.webPerms = getFieldValue(row, 'menuWebPerms') || getFieldValue(row, 'webPerms') || row.name || '';
      form.apiPerms = getFieldValue(row, 'menuApiPerms') || getFieldValue(row, 'apiPerms') || '';
      form.component = getFieldValue(row, 'menuComponent') || getFieldValue(row, 'component') || '';
      form.icon = getFieldValue(row, 'menuIcon') || getFieldValue(row, 'icon') || '';
      form.sort = getFieldValue(row, 'menuSort') || getFieldValue(row, 'sort') || 1;
      form.visibleFlag = getFieldValue(row, 'menuVisibleFlag') ?? getFieldValue(row, 'visibleFlag') ?? 1;
      form.frameFlag = getFieldValue(row, 'menuFrameFlag') ?? getFieldValue(row, 'frameFlag') ?? 0;
      form.frameUrl = getFieldValue(row, 'menuFrameUrl') || getFieldValue(row, 'frameUrl') || '';
      form.disabledFlag = getFieldValue(row, 'menuDisabledFlag') ?? getFieldValue(row, 'disabledFlag') ?? 0;
    } else {
      form.id = row.id || 0;
      form.authName = getFieldValue(row, 'menuName') || getFieldValue(row, 'title') || '';
      form.webPerms = getFieldValue(row, 'menuWebPerms') || getFieldValue(row, 'webPerms') || row.authMark || '';
      form.apiPerms = getFieldValue(row, 'menuApiPerms') || getFieldValue(row, 'apiPerms') || '';
      form.authSort = getFieldValue(row, 'menuSort') || getFieldValue(row, 'sort') || 1;
      form.parentId = row.menuParentId === 0 ? 0 : (row.menuParentId ?? null);
    }
  }

  /**
   * 表单提交处理函数
   * 更新菜单数据并触发刷新事件
   */
  const handleSubmit = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          loading.value = true;
          const menuData = {
            menuName: form.name,
            menuPath: fullMenuPath.value,
            menuComponent: form.component,
            menuIcon: form.icon,
            menuSort: form.sort,
            menuVisibleFlag: form.visibleFlag,
            menuFrameFlag: form.frameFlag,
            menuFrameUrl: form.frameUrl,
            menuWebPerms: form.webPerms,
            menuApiPerms: form.apiPerms,
            menuDisabledFlag: form.disabledFlag,
            menuParentId: form.parentId === null ? 0 : form.parentId,
            menuType: menuType.value === 'menu' ? 1 : 2,
            id: form.id
          };

          // 添加调试信息
          console.log('[Menu Edit] 提交的菜单数据:', menuData);
          
          // 确保ID存在
          if (!form.id) {
            ElMessage.warning('菜单ID不能为空');
            loading.value = false;
            return;
          }

          const res = await apiRbacMenuUpdateDataUsingPost({ body: menuData });
          
          console.log('[Menu Edit] API响应结果:', res);
          
          if (res && (res === true || (typeof res === 'object' && res.code === 0))) {
            ElMessage.success('编辑成功');
            emit('submit', { ...form });
            handleCancel();
          } else {
            const errorMsg = (res && typeof res === 'object' && res.msg) ? res.msg : '编辑失败';
            ElMessage.error(errorMsg);
          }
        } catch (error: any) {
          const errorMessage = error.message || '未知错误';
          console.error('菜单保存失败:', error);
          ElMessage.error(`编辑失败: ${errorMessage}`);
        } finally {
          loading.value = false;
        }
      }
    });
  }

  /**
   * 取消处理函数
   */
  const handleCancel = () => {
    emit('update:visible', false);
  }

  /**
   * 关闭处理函数
   */
  const handleClosed = () => {
    resetForm();
  }

  /**
   * 监听visible属性变化
   */
  watch(
    () => props.visible,
    (newVal) => {
      if (newVal) {
        nextTick(() => {
          initForm();
        });
      }
    },
    { immediate: true } 
  );
  
  // 新增对editData的监听，确保数据更新后能正确加载到表单中
  watch(
    () => props.editData,
    (newVal) => {
      if (props.visible && newVal) {
        nextTick(() => {
          loadFormData();
        });
      }
    },
    { deep: true }
  );
</script>

<style scoped>
.path-prefix {
  font-size: 14px;
  color: #666;
  margin-right: 4px;
  white-space: nowrap;
}
</style>